﻿// See https://aka.ms/new-console-template for more information


Console.WriteLine($"主线程ID：" + Thread.CurrentThread.ManagedThreadId);

//ThreadPoolTest();

//Task
TaskTest();

//async 
await AsyncTest();

Console.Read();

void ThreadPoolTest()
{
    for (int i = 0; i < 10; i++)
    {
        var n = i;
        //ThreadPool执行任务
        ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
        {
            Console.WriteLine($"执行{n}");
            Thread.Sleep(5000);
            Console.WriteLine($"第{obj}个执行任务__{DateTime.Now.ToString("HH:mm:ss:fff:ffffff")}_{n}_{Thread.CurrentThread.ManagedThreadId}");
        }), i);
    }
}

void TaskTest()
{
    List<Task> tasks = new List<Task>();
    for (int i = 0; i < 10; i++)
    {
        var n = i;
        tasks.Add(new Task(() =>
        {
            Console.WriteLine($"执行{n}");
            var t = new Task(() =>
            {
                Thread.Sleep(5000);
            });
            t.Start();
            t.Wait();
            Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff:ffffff")}_{n}_{Thread.CurrentThread.ManagedThreadId}");
        }));
        tasks[i].Start();
    }
    Task.WaitAll(tasks.ToArray());
    Console.WriteLine("所有任务执行完成");
}

async Task AsyncTest()
{
    List<Task<int>> list = new List<Task<int>>();
    for (int i = 0; i < 10; i++)
    {
        list.Add(AsyncFunction(i));
    }

    Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff:ffffff")}_做其他事__{Thread.CurrentThread.ManagedThreadId}");

    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(await list[i] + "执行完成");
    }
}

async Task<int> AsyncFunction(int index)
{
    Console.WriteLine($"{index}工作了");
    await sleep();//请求网络5秒钟
    Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff:ffffff")}_{index}__{Thread.CurrentThread.ManagedThreadId}");
    return index;
}

async Task sleep()
{
    var t = new Task(() =>
    {
        Thread.Sleep(5000);
    });
    t.Start();
    await t;
}